#include "DatabaseManager.h"

DatabaseManager::DatabaseManager()
{
    if(sqlite3_open("community.db",&db) != SQLITE_OK)
    {
        cerr << "Can't open database: " << sqlite3_errmsg(db) << endl;
    }
    else
    {
    char* errMsg = nullptr;

    //创建一个表格  内容为id username password 
    string str = "CREATE TABLE IF NOT EXISTS accounts("
     "id INTEGER PRIMARY KEY AUTOINCREMENT,"
     "userID INTEGER NOT NULL UNIQUE,"
     "username TEXT NOT NULL,"
     "password TEXT NOT NULL,"
     "phonenum INTEGER NOT NULL)";
    if(sqlite3_exec(db,str.c_str(),nullptr,nullptr,&errMsg) != SQLITE_OK)
    {
        cerr << "sql error:" << errMsg << endl;
        //释放错误信息
        sqlite3_free(errMsg);
    }
    }
}

DatabaseManager::~DatabaseManager()
{
    //如果这个数据库还存在那么就关闭他
    if(db)
    {
        sqlite3_close(db);
    }
}


//对数据库中的内容进行二进制转换
sqlite3_stmt* DatabaseManager::prepare(const string &sql)
{
    sqlite3_stmt* stmt = nullptr;
    //这个-1是表示自动计算长度
    if(sqlite3_prepare_v2(db,sql.c_str(),-1,&stmt,nullptr) != SQLITE_OK)
    {
        cerr << "prepare failed: " << sqlite3_errmsg(db) << endl;
        return nullptr;
    }
    return stmt;
}
